package com.lvmama.search.spider.config;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHost;
import org.apache.http.client.CookieStore;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.lvmama.search.spider.proxy.ProxyIp;
import com.lvmama.search.spider.proxy.ProxyManager;

/**
 * 上下文信息
 * @author 1
 *
 */
public class Context {
	
	private static Log log=LogFactory.getLog(Context.class);
	
	private static TransmittableThreadLocal<CloseableHttpClient> httpClients=new TransmittableThreadLocal<CloseableHttpClient>();
	
	private static TransmittableThreadLocal<HttpClientContext> httpClientContexts=new TransmittableThreadLocal<HttpClientContext>();
	
	private static TransmittableThreadLocal<HttpHost> httpProxy=new TransmittableThreadLocal<HttpHost>();
	
	public static void setHttpProxy() {
		 ProxyIp ip=ProxyManager.getProxyIp();
		 if(ip!=null) {
			 HttpHost host=new HttpHost(ip.getIp(), ip.getPort(), ip.getScheme());
			 httpProxy.set(host);
		 }else {
			 log.warn("no proxy ip available");
		 }
	}
	
	public static HttpHost getHttpProxy() {
		return httpProxy.get();
	}
	
	public static void removeHttpProxy() {
		 httpProxy.remove();
	}
	
	public static void initHttpContext() {
    	HttpClientContext httpClientContext=httpClientContexts.get();
		if(httpClientContext==null) {
			httpClientContext=createHttpClientContext();
			httpClientContexts.set(httpClientContext);
		}
	}

    public static HttpClientContext getHttpClientContext() {
    	return httpClientContexts.get();
	}
    
    private static HttpClientContext createHttpClientContext() {
        CookieStore cookieStore = new BasicCookieStore();
        // Create local HTTP context
        HttpClientContext localContext = HttpClientContext.create();
        // Bind custom cookie store to the local context
        localContext.setCookieStore(cookieStore);
        return localContext;
	}
	
    public static void initHttpClient() {
    	CloseableHttpClient httpClient=httpClients.get();
		if(httpClient==null) {
			httpClient=createHttpClient();
			httpClients.set(httpClient);
		}
	}
    
    public static CloseableHttpClient getHttpClient() {
    	return httpClients.get();
	}
    
	private static CloseableHttpClient createHttpClient() {
		return HttpClients.createDefault();
	}
	
	public void closeHttpClient() {
		CloseableHttpClient client=httpClients.get();
		if(client!=null) {
			try {
				client.close();
			} catch (IOException e) {
				log.error("error to close http client:",e);
			}
			httpClients.remove();
		}
	}
	
	
}
